'use client';

import { formatCurrency } from '@/utils/common';
import Link from 'next/link';
import { useEffect, useRef, useState } from 'react';

const FilterSection = ({
  title,
  type,
  datakey,
  data,
  basePath,
  filtersData,
  loginTipsVisible,
  onChange,
  defaultCollapse,
}: FilterSectionProps) => {
  const [expand, setExpand] = useState<boolean>(
    loginTipsVisible && defaultCollapse != undefined ? !defaultCollapse : true
  );
  const [options, setOptions] = useState<FilterData[]>(data || []);

  const toogleExpand = () => {
    setExpand(e => !e);
  };

  const [loginURL, setLoginURL] = useState('');
  const [signupURL, setSignupURL] = useState('');
  const getLoginURL = () => {
    const url =
      process.env.NEXT_PUBLIC_LOGIN_URL +
      '?return_url=' +
      encodeURIComponent(
        location.origin + '/api/login?backurl=' + window.location.href
      );
    return url;
  };
  const getSignupURL = () => {
    const url = 'https://web.dropshipzone.com.au/get-started/sign-up';
    // process.env.NEXT_PUBLIC_DSZ_DOMAIN + '/customer/account/create/';
    return url;
  };
  useEffect(() => {
    setLoginURL(getLoginURL());
    setSignupURL(getSignupURL());
  }, []);
  useEffect(() => {
    loginTipsVisible && defaultCollapse && setExpand(false);
  }, [loginTipsVisible, defaultCollapse]);

  const handleCheckChange = (e: any) => {
    const elm = e.currentTarget;
    if (elm.checked) {
      onChange && onChange('add', { ...elm.dataset });
    } else {
      onChange && onChange('del', { ...elm.dataset });
    }
  };

  const handleRadioClick = (e: any) => {
    const elm = e.currentTarget;
    const currRadio = getCurrentFilterByKey(elm.dataset.datakey);
    if (currRadio == elm.dataset.value) {
      elm.checked = false;
      onChange && onChange('del', { ...elm.dataset });
    } else {
      elm.checked = true;
      onChange && onChange('add', { ...elm.dataset });
    }
  };

  const getCurrentFilterByKey = (key: any) => {
    if (filtersData && filtersData[key] != undefined) {
      return filtersData[key].value;
    }
    return null;
  };

  const checkRadioRef = useRef<any>([]);
  const changeFiltersView = () => {
    if (type == 'checkbox' || type == 'radio') {
      options?.forEach((item: any, index) => {
        if (!getCurrentFilterByKey(item.datakey)) {
          checkRadioRef.current[index].checked = false;
        }
      });
    }
  };
  const filterChangeRef = useRef(changeFiltersView);
  filterChangeRef.current = changeFiltersView;

  useEffect(() => {
    filterChangeRef.current();
  }, [filtersData]);
  useEffect(() => {
    data && setOptions(data);
  }, [data]);

  return (
    <div className="side-section">
      <div className="side-section-title" onClick={toogleExpand}>
        <span>{title}</span>
        <span
          className={`side-section-expand-icon iconfont icon-expand-line ${expand ? 'expand-icon-up' : 'expand-icon-down'}`}
        ></span>
      </div>
      <div
        className={`side-section-content thin-scroll-bar ${expand ? 'content-expand' : 'content-collapse'}`}
      >
        <div className="side-section-list">
          {loginTipsVisible ? (
            <div className="side-section-login-tips">
              <Link href={signupURL}>Sign up</Link> or{' '}
              <Link href={loginURL}>Login</Link> to use this feature.
            </div>
          ) : type == 'checkbox' ? (
            options?.map((item: any, index) => (
              <div className="side-section-item" key={index}>
                <label className="side-section-item-label">
                  <span className="side-section-item-checkbox">
                    <input
                      type="checkbox"
                      ref={(el: any) => (checkRadioRef.current[index] = el)}
                      data-datakey={item.datakey}
                      data-value={item.value}
                      data-title={item.title}
                      data-type={item.type}
                      value={item.value}
                      onChange={handleCheckChange}
                      defaultChecked={
                        getCurrentFilterByKey(item.datakey) ==
                        item.value.toString()
                      }
                    />
                    <span className="side-section-item-uncheckmark iconfont icon-checkbox-unchecked"></span>
                    <span className="side-section-item-checkedmark iconfont icon-checkbox-checked"></span>
                  </span>
                  {item.title}
                </label>
                {item.number !== undefined && (
                  <span className="side-section-item-number">
                    ({item.number})
                  </span>
                )}
              </div>
            ))
          ) : type == 'radio' ? (
            options?.map((item: any, index) => (
              <div className="side-section-item" key={index}>
                <label className="side-section-item-label">
                  <span className="side-section-item-checkbox">
                    <input
                      type="radio"
                      ref={(el: any) => (checkRadioRef.current[index] = el)}
                      data-datakey={item.datakey}
                      data-value={item.value}
                      data-title={item.title}
                      data-type={item.type}
                      name={item.datakey}
                      value={item.value}
                      onClick={handleRadioClick}
                      defaultChecked={
                        getCurrentFilterByKey(item.datakey)?.toString() ==
                        item.value.toString()
                      }
                    />
                    <span className="side-section-item-uncheckmark iconfont icon-checkbox-unchecked"></span>
                    <span className="side-section-item-checkedmark iconfont icon-checkbox-checked"></span>
                  </span>
                  {item.title}
                </label>
                {item.number !== undefined && (
                  <span className="side-section-item-number">
                    ({item.number})
                  </span>
                )}
              </div>
            ))
          ) : (
            ''
          )}
        </div>
      </div>
    </div>
  );
};

export default FilterSection;
